package elephant.servers.gameserver.connect;

import java.util.Date;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import elephant.servers.gameserver.codec.RequestMessage;
import elephant.servers.gameserver.core.GameRequest;
import elephant.servers.gameserver.core.GameRequestDispatch;
import elephant.servers.gameserver.session.GameSession;
import elephant.servers.gameserver.session.GameSessionManager;
import io.netty.channel.ChannelHandler.Sharable;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.util.AttributeKey;

/**
 * 
 * @author icecooly
 *
 */
@Sharable
public class GameServerHandler extends ChannelInboundHandlerAdapter{
	//
    private static final Logger logger = LoggerFactory.getLogger(
    		GameServerHandler.class);
    
    private static final AttributeKey<GameSession> SESSION_KEY=
			AttributeKey.valueOf("s");

    private GameSessionManager sessionManager;
    private GameRequestDispatch requestDispatcher;
    //
    
    //
    public GameServerHandler(GameSessionManager sessionManager,GameRequestDispatch requestDispatcher){
    	this.sessionManager=sessionManager;
    	this.requestDispatcher=requestDispatcher;
    }
    
    
    @Override
	public void channelActive(ChannelHandlerContext ctx) throws Exception {
		GameSession session=new GameSession(ctx.channel());
		ctx.channel().attr(SESSION_KEY).set(session);
		sessionManager.sessionCreated(session);
		if(logger.isDebugEnabled()){
    		logger.debug("channelActive "+ctx.channel());
    	}
	}
    
    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
    	GameSession session=ctx.channel().attr(SESSION_KEY).get();
    	sessionManager.sessionDisconnected(session);
    	if(logger.isDebugEnabled()){
    		logger.debug("channelInactive "+ctx.channel());
    	}
	}
	/**
	 * 
	 */
	@Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
		RequestMessage message=(RequestMessage) msg;
		if(logger.isDebugEnabled()){
			logger.debug("channelRead "+msg);
		}
		//
		GameRequest request=new GameRequest();
		request.startTime=System.currentTimeMillis();
		request.requestId=message.requestId;
		request.serviceId=message.serviceId;
		request.bodySerializeType=message.bodySerializeType;
		request.requestParameters=message.body;
//		//
		request.session=ctx.channel().attr(SESSION_KEY).get();
		request.session.setBodySerializeType(message.bodySerializeType);
//		//
		requestDispatcher.dispatch(request);
	}
	
	@Override
	public void userEventTriggered(ChannelHandlerContext ctx, Object evt)
			throws Exception {
		if(evt instanceof IdleStateEvent){  
			GameSession session=ctx.channel().attr(SESSION_KEY).get();
			session.kick("user idle 5 minutes,last access:"+
									new Date(session.getLastAccessTime()));
        }    
	}	
}

